<template>
	<div class="settlement-manage-container">
		<!-- 基本信息 -->
		<h1 class="text-center"><b>结算单</b></h1>
		<div class="toolbar">
			<a-row justify="space-between">
				<a-col :span="2">基本信息</a-col>
				<a-col :span="2" class="text-right">
					<a-tag v-if="!info.id && info.supplier_audit === 0" :bordered="false" color="processing">初始化</a-tag>
					<a-tag v-else-if="info.supplier_audit === 1" :bordered="false" color="processing">供应商未审核</a-tag>
					<a-tag v-else-if="info.supplier_audit === 3" :bordered="false" color="error">供应商退回</a-tag>
				</a-col>
			</a-row>
			<a-divider style="margin: 10px 0 10px 0;" />
			<a-form ref="searchRef" :model="info">
				<a-descriptions bordered size="small">
					<a-descriptions-item label="所属单位">{{ info.project?.name }}</a-descriptions-item>
					<a-descriptions-item label="结算单据编号">{{ info.code }}</a-descriptions-item>
					<a-descriptions-item label="合同名称">{{ info.contract?.name }}</a-descriptions-item>
					<a-descriptions-item label="对方单位名称">{{ info.supplier?.company_name }}</a-descriptions-item>
					<a-descriptions-item label="合同类型">{{ info.contract_type }}</a-descriptions-item>
					<a-descriptions-item label="所签合同结算合计">{{ info.history_settle_amount }}</a-descriptions-item>
					<a-descriptions-item label="暂定合同总金额">{{ info.contract_amount }}</a-descriptions-item>
					<a-descriptions-item label="末次结算">
						{{ info.is_end? '是' : '否' }}
					</a-descriptions-item>
					<a-descriptions-item>
						<template #label>
							<span style="color: red">* </span>发票类型
						</template>
						<span>{{ info.invoice_type }}</span>
					</a-descriptions-item>
					<a-descriptions-item>
						<template #label>
							<span style="color: red">* </span>采购方式
						</template>
						<span>{{ info.purchase_way?.name }}</span>
					</a-descriptions-item>
					<a-descriptions-item>
						<template #label>
							<span style="color: red">* </span>采购类型
						</template>
						<span>{{ info.purchase_type?.name }}</span>
					</a-descriptions-item>
					<a-descriptions-item>
						<template #label>
							<span style="color: red">* </span>业务日期
						</template>
						<span>{{ info.settle_date }}</span>
					</a-descriptions-item>
					<a-descriptions-item label="进入成本金额">{{ info.without_tax_amount || 0 }}</a-descriptions-item>
					<a-descriptions-item label="可抵扣进项税额">{{ info.tax_amount || 0 }}</a-descriptions-item>
					<a-descriptions-item label="结算金额"><span style="color: red;">{{ info.amount }}</span></a-descriptions-item>
					<a-descriptions-item label="调差总额">{{ info.deduct_amount || 0 }}</a-descriptions-item>
					<a-descriptions-item label="应付金额">{{ info.payable_amount || 0 }}</a-descriptions-item>
					<a-descriptions-item label="附件张数">{{ info.files?.length || 0 }}</a-descriptions-item>
					<a-descriptions-item label="合同已结算比率">{{ info.contract_settle_ratio || 0 }}%</a-descriptions-item>
					<a-descriptions-item>
						<template #label>
							<span style="color: red">* </span>单据名称
						</template>
						<span>{{ info.name }}</span>
					</a-descriptions-item>
					<a-descriptions-item label="备注">
						<span>{{ info.memo }}</span>
					</a-descriptions-item>
				</a-descriptions>
			</a-form>
		</div>
		<!-- tab切换表格 -->
		<div class="tab">
			<a-tabs v-model:activeKey="activeKey">
				<a-tab-pane key="1" tab="本次材料汇总">
					<a-table
						:columns="getMaterialColumns"
						:data-source="info.materials"
						bordered
						size="small"
						:scroll="{ y: 240 }"
						:pagination="false"
					>
						<template #bodyCell="{ column, record }">
							<template v-if="['up_per_rate', 'up_per_price'].includes(column.dataIndex)">
								<span>{{ record.up_per }}</span>
							</template>
							<template v-if="column.dataIndex === 'price'">
								<span v-if="record.price || parseFloat(record.price) ===0">{{ record.price }}</span>
								<span v-else style="color: red">未获取到价格<br />验收时间{{ record.ys_date }}</span>
							</template>
							<template v-if="['without_tax_subprice', 'with_tax_subprice', 'without_tax_amount', 'with_tax_amount', 'tax_amount'].includes(column.dataIndex)">
								<span v-if="record[column.dataIndex] || parseFloat(record[column.dataIndex]) ===0">{{ record[column.dataIndex] }}</span>
								<span v-else style="color: red">暂无</span>
							</template>
							<template v-if="column.dataIndex === 'memo'">
								<span>{{ record.memo }}</span>
							</template>
						</template>
						<template #summary>
							<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
								<a-table-summary-cell :col-span="3" class="text-center">
									<a-typography-text>合计</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell :col-span="5"></a-table-summary-cell>
								<a-table-summary-cell v-if="[2, 3].includes(info.contract?.price_type)" :col-span="2"></a-table-summary-cell>
								<a-table-summary-cell v-if="[3, 5].includes(info.contract?.type)"></a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ add(info.materials?.map(item => item.without_tax_amount), 2) }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ add(info.materials?.map(item => item.with_tax_amount), 2) }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell class="text-center">
									<a-typography-text>{{ add(info.materials?.map(item => item.tax_amount), 2) }}</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
								<a-table-summary-cell></a-table-summary-cell>
							</a-table-summary-row>
						</template>
					</a-table>
				</a-tab-pane>
				<a-tab-pane key="3" tab="费用分类">
					<a-space direction="vertical">
						<a-table
							:columns="priceColumns"
							:data-source="info.material_type_collect"
							bordered
							size="small"
							:pagination="false"
							:scroll="{ y: 240 }"
						>
						</a-table>
					</a-space>
				</a-tab-pane>
				<a-tab-pane key="4" tab="附件信息">
					<a-space direction="vertical">
						<a-row :gutter="20" justify="space-between">
							<a-col :span="4">
								附件张数:{{ info.files.length }}张
							</a-col>
						</a-row>
						<a-table
							:columns="annexColumns"
							:data-source="info.files"
							bordered
							:loading="uploading"
							size="small"
							:pagination="false"
							:scroll="{ y: 400 }"
						>
							<template #bodyCell="{ column, record }">
								<template v-if="column.dataIndex === 'file_name'">
									<a-input v-if="record.is_edit" v-model:value="record.file_name" />
									<span v-else>{{ record.file_name }}</span>
								</template>
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button v-if="record.uid === 0" type="primary" size="small" :target="record.file_name" @click="printElement('file_settlement_price_verify')">
											<DownloadOutlined />
										</a-button>
										<a-button v-else type="primary" size="small" :href="record.url" :target="record.file_name">
											<DownloadOutlined />
										</a-button>
										<a-button v-if="/\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(record.url)" size="small" @click="record.visible = true">
											<EyeOutlined />
											<a-image
												:width="0"
												:style="{ display: 'none' }"
												:preview="{
													visible: record.visible,
													onVisibleChange: setVisible(record),
												}"
												:src="record.url"
											/>
										</a-button>
									</a-space>
								</template>
							</template>
						</a-table>
					</a-space>
				</a-tab-pane>
				<a-tab-pane key="5" tab="合同链接明细">
					<a-table
						:columns="contractColumns"
						:data-source="[info.contract]"
						bordered
						size="small"
						:scroll="{ y: 240 }"
						:pagination="false"
					>
						<template #bodyCell="{ column }">
							<template v-if="column.key === 'operation'">
								<a-space>
									<a-button type="primary" size="small" @click="router.push(`/contract/info/${info.contract?.id}`)">
										<EyeOutlined />
									</a-button>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-tab-pane>
			</a-tabs>
		</div>
		<!-- 其他结算明细表格 -->
		<div class="detail pt-2">
			<a-collapse v-model:activeKey="detailKey" ghost>
				<template #expandIcon="{ isActive }">
					<caret-right-outlined :rotate="isActive ? 90 : 0" />
				</template>
				<a-collapse-panel key="1" header="其他结算明细">
					<a-table
						:columns="otherColumns"
						:data-source="info.other_settle_detail"
						bordered
						size="small"
						:pagination="false"
					>
						<template #bodyCell="{ column, record }">
							<template v-if="['project_technology', 'business', 'finance', 'safe_quality', 'office'].includes(column.dataIndex)">
								<span> {{ record[column.dataIndex] }}</span>
							</template>
						</template>
					</a-table>
				</a-collapse-panel>
			</a-collapse>
		</div>
		<a-row>
			<a-col v-if="info.supplier_audit === 3" :span="24">供应商退回理由: <span style="color: red;">{{ info.supplier_audit_memo || '' }}</span></a-col>
		</a-row>
		<!--    分供结算价款确认-->
		<div id="file_settlement_price_verify" class="p-5" style="display: none;">
			<div class="container">
				<div class="page">
					<a-row>
						<a-col :span="24" class="text-center"><h4><b>分供结算价款确认</b></h4></a-col>
					</a-row>
					<a-row>
						<a-col :span="5" class="text-right"><b>确认日期：</b></a-col>
						<a-col :span="19" class="px-2 underline text-center">
							{{ info.supplier_audit_time? dayjs(info.supplier_audit_time).format('YYYY-MM-DD HH:mm:ss') : '' }}
						</a-col>
					</a-row>
					<a-row>
						<a-col :span="5" class="text-right"><b>本期结算金额</b></a-col>
						<a-col :span="3" class="px-2 underline text-center">{{ info.amount }}</a-col>
						<a-col :span="8">
							<a-row>
								<a-col :span="14"><b>元，其中不含税金额</b></a-col>
								<a-col :span="10" class="px-2 underline text-center">{{ info.without_tax_amount }}</a-col>
							</a-row>
						</a-col>
						<a-col :span="8">
							<a-row>
								<a-col :span="7"><b>元，税金</b></a-col>
								<a-col :span="15" class="px-2 underline text-center">{{ info.tax_amount }}</a-col>
								<a-col :span="2"><b>元</b></a-col>
							</a-row>
						</a-col>
					</a-row>
					<a-row>
						<a-col :span="5" class="text-right"><b>开累结算金额</b></a-col>
						<a-col :span="3" class="px-2 underline text-center">{{ info.history_settle_price?.amount }}</a-col>
						<a-col :span="8">
							<a-row>
								<a-col :span="14"><b>元，其中不含税金额</b></a-col>
								<a-col :span="10" class="px-2 underline text-center">{{ info.history_settle_price?.without_tax_amount }}</a-col>
							</a-row>
						</a-col>
						<a-col :span="8">
							<a-row>
								<a-col :span="7"><b>元，税金</b></a-col>
								<a-col :span="15" class="px-2 underline text-center">{{ info.history_settle_price?.tax_amount }}</a-col>
								<a-col :span="2"><b>元</b></a-col>
							</a-row>
						</a-col>
					</a-row>
					<br />
					<br />
					<a-row>
						<a-col :span="24" class="text-center"><h4><b>分供单位</b></h4></a-col>
					</a-row>
					<a-row>
						<a-col :span="5" class="text-right"><b>分供单位：</b></a-col>
						<a-col :span="19" class="px-2 underline text-center">{{ info.supplier?.company_name }}</a-col>
					</a-row>
					<a-row>
						<a-col :span="5"></a-col>
						<a-col :span="19" class="text-center font-size-10">(分供单位公章)</a-col>
					</a-row>
					<br />
					<a-row>
						<a-col :span="5" class="text-right"><b>法人或授权委托人：</b></a-col>
						<a-col :span="19" class="px-2 underline text-center">{{ info.supplier?.fullname }}</a-col>
					</a-row>
					<a-row>
						<a-col :span="5"></a-col>
						<a-col :span="19" class="text-center font-size-10">(签字确认)</a-col>
					</a-row>
					<a-row>
						<a-col :span="5" class="text-right"><b>编制人：</b></a-col>
						<a-col :span="19" class="px-2 underline text-center">{{ info.opr?.fullname }}</a-col>
					</a-row>
				</div>
			</div>
		</div>
		<a-card class="workflow" title="审批流" size="small">
			<a-workflow v-if="info.id && info.supplier_audit === 2" v-model:status="info.workflow_status" module="settleCourse" :target-id="info.id" :project-id="info.project_id" :code="info.code" :user-id="info.opr_id" :extra="true" :steps="true" @submit="(e) => console.log(e)"></a-workflow>
		</a-card>
		<a-row :gutter="20">
			<a-col :span="24" class="py-4 text-center">
				<a-space>
					<!--					<a-workflow v-if="info.id" v-model:status="info.workflow_status" module="contract" :target-id="info.id" :project-id="info.project_id" :code="info.code" :user-id="info.opr_id" @submit="submitPurchase"></a-workflow>-->
					<a-button @click="toReturn">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
	</div>
</template>
<script setup lang="jsx">
import { reactive, ref, computed, getCurrentInstance, onMounted, watch, inject } from "vue";
import {
	FormOutlined,
	EyeOutlined,
	UploadOutlined,
	SyncOutlined,
	DownloadOutlined,
	EditOutlined,
	SaveOutlined,
	DeleteOutlined,
	CaretRightOutlined,
	ImportOutlined, LoadingOutlined, CloseOutlined
} from '@ant-design/icons-vue'
import { post, postJson } from "../utils";
import { useRoute, useRouter } from "vue-router";
import { add, subtract } from "@/utils/operation.js";
import { baseURL } from "@/utils/request.js";
import { userStore } from "@/store/index.js";
import { cloneDeep } from "lodash-es";
import dayjs from "dayjs";
import { AWorkflow } from "@/components/index.js";
import { printElement } from "@/utils/exportData.js";
const route = useRoute();
const router = useRouter();
const query = route.query;
const searchState = reactive({}); // 表单数据
const activeKey = ref('1'); // tab 默认数据
const { proxy } = getCurrentInstance();
const uploading = ref(false);
const store = userStore();
const userInfo = store.info;

const info = ref({});
const materialColumns = [
	{
		title: "序号",
		dataIndex: "key",
		width: 60,
		align: "center",
		fixed: 'left',
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	// {
	// 	title: '物资编码',
	// 	dataIndex: 'name',
	// 	key: 'name',
	// 	width: 100,
	// 	fixed: 'left',
	// 	align: 'center',
	// },
	{
		title: '物资名称',
		dataIndex: 'name',
		width: 100,
		align: 'center',
		fixed: 'left',
	},
	{
		title: '规格型号',
		dataIndex: 'model',
		width: 100,
		align: 'center',
		fixed: 'left',
	},
	{
		title: '计量单位',
		dataIndex: 'unit',
		width: 100,
		align: 'center',
		fixed: 'left',
	},
	{
		title: '发票',
		children: [
			{
				title: '增值税率(%)',
				dataIndex: 'tax_rate',
				width: 100,
				align: 'center',
			},
			{
				title: '浮动比率±(%)',
				dataIndex: 'up_per_rate',
				width: 100,
				align: 'center',
			},
			{
				title: '浮动价格(±)',
				dataIndex: 'up_per_price',
				width: 100,
				align: 'center',
			},
			{
				title: '项目部',
				children: [
					{
						title: '数量',
						dataIndex: 'quantity',
						width: 100,
						align: 'center',
					},
					{
						title: '时长',
						dataIndex: 'use_time',
						width: 100,
						align: 'center',
					},
					{
						title: '信息价',
						dataIndex: 'price',
						width: 130,
						align: 'center',
					},
					{
						title: '不含增值税单价',
						dataIndex: 'without_tax_subprice',
						width: 130,
						align: 'center',
					},
					{
						title: '含增值税单价',
						dataIndex: 'with_tax_subprice',
						width: 130,
						align: 'center',
					},
					{
						title: '不含增值税金额',
						dataIndex: 'without_tax_amount',
						width: 130,
						align: 'center',
					},
					{
						title: '含增值税金额',
						dataIndex: 'with_tax_amount',
						width: 130,
						align: 'center',
					},
					{
						title: '增值税额',
						dataIndex: 'tax_amount',
						width: 130,
						align: 'center',
					},
				],
			},
		],
	},
	{
		title: '至本次钱开累计算(含税)',
		children: [
			{
				title: '数量',
				dataIndex: 'total_settle_quantity',
				width: 100,
				align: 'center',
			},
			{
				title: '金额',
				dataIndex: 'total_settle_amount',
				width: 100,
				align: 'center',
			},
		],
	},
	{
		title: '备注',
		dataIndex: 'memo',
		width: 80,
		fixed: 'right',
		align: 'center',
	},
];
const getMaterialColumns = computed(() => {
	let _materialColumns = cloneDeep(materialColumns);
	const filterDataIndex = (sources, removeIndexes) => {
		const list = [];
		for (const item of sources) {
			if (!removeIndexes.includes(item.dataIndex)) {
				if (item.children) {
					item.children = filterDataIndex(item.children, removeIndexes);
				}
				list.push(item);
			}
		}
		return list;
	}
	switch (info.value.contract?.price_type) {
	case 2:
		_materialColumns = filterDataIndex(_materialColumns, ['up_per_price'])
		break;
	case 3:
		_materialColumns = filterDataIndex(_materialColumns, ['up_per_rate'])
		break;
	default:
		_materialColumns = filterDataIndex(_materialColumns, ['up_per_rate', 'up_per_price', 'price'])
		break;
	}
	if (![3, 5].includes(info.value.contract?.type)) {
		_materialColumns = filterDataIndex(_materialColumns, ['use_time'])
	}
	return _materialColumns;
})

const setVisible = (record) => {
	return (visible = false) => {
		record.visible = visible;
	}
}

const priceColumns = [
	{
		title: "序号",
		dataIndex: "key",
		width: 60,
		align: "center",
		fixed: 'left',
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: '材料类型',
		dataIndex: 'ys_type_name',
		align: "left",
	},
	{
		title: '金额',
		dataIndex: 'amount',
		width: 150,
		align: "center",
	},
];


// 合同链接明细数据事件开始
// 折叠面板默认值
const detailKey = ref(1)
// 表头
const otherColumns = [
	{
		title: '项目名称',
		dataIndex: 'name',
		key: 'name',
		fixed: 'left',
		customRender: ({ text, record, index, column }) => {
			return `${text}(${record.type})`;
		}
	},
	{
		title: '工程技术部',
		dataIndex: 'project_technology',
		width: 100,
		align: 'center',
	},
	{
		title: '商务管理部',
		dataIndex: 'business',
		width: 100,
		align: 'center',
	},
	{
		title: '财务部',
		dataIndex: 'finance',
		width: 100,
		align: 'center',
	},
	{
		title: '安质部',
		dataIndex: 'safe_quality',
		width: 100,
		align: 'center',
	},
	{
		title: '办公室',
		dataIndex: 'office',
		width: 100,
		align: 'center',
	},
];

// 表头
const contractColumns = [
	{
		title: "序号",
		dataIndex: "key",
		width: 60,
		align: "center",
		fixed: 'left',
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: '是否主合同',
		dataIndex: 'is_main',
		width: 100,
		fixed: 'left',
		align: 'center',
		customRender: ({ text, record, index, column }) => {
			return '是';
		}
	},
	{
		title: '合同名称',
		dataIndex: 'name',
		align: 'center',
	},
	{
		title: '合同编号',
		dataIndex: 'code',
		width: 220,
		align: 'center',
	},
	// {
	// 	title: '公司合同编号',
	// 	dataIndex: 'code2',
	// 	width: 150,
	// 	align: 'center',
	// },
	{
		title: '签订时间',
		dataIndex: 'update_time',
		width: 170,
		align: 'center',
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 70,
		align: "center"
	}
];

// 其他结算明细数据事件开始
// 表头
const annexColumns = [
	{
		title: "序号",
		dataIndex: "key",
		width: 50,
		align: "center",
		fixed: 'left',
		customRender: ({ text, record, index, column }) => {
			return index + 1;
		}
	},
	{
		title: '附件名称',
		dataIndex: 'file_name',
	},
	{
		title: '文件大小',
		dataIndex: 'size',
		width: 80,
		align: 'center',
	},
	{
		title: '创建人',
		dataIndex: 'opr_name',
		width: 70,
		align: 'center',
	},
	{
		title: '创建时间',
		dataIndex: 'create_time',
		width: 150,
		align: 'center',
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 150,
		align: "center"
	}
];

onMounted(async () => {
	try {
		info.value = await postJson('settlement/info', {
			id: query.id || null,
			supply_order_ids: query.supply_order_ids ? query.supply_order_ids.split(',').map(item => parseInt(item)) : [],
			contract_id: parseInt(query.contract_id) || null,
		})
		if (info.value.supplier_audit === 2) {
			info.value.files = [
				{
					uid: 0,
					file_name: '分供结算价款确认单',
					url: '',
					opr_name: info.value.supplier?.fullname || '',
					create_time: dayjs(info.value.supplier_audit_time).format('YYYY-MM-DD HH:mm:ss'),
				},
				...info.value.files,
			]
		}
	} catch (e) {
		proxy.$message.error(e.message || e);
	}

})
// 其他结算明细数据事件结束
watch(() => info.value.other_settle_detail, () => {
	info.value.deduct_amount = info.value.other_settle_detail.reduce((target, item) => {
		const keys = ['project_technology', 'business', 'finance', 'safe_quality', 'office'];
		const sum = keys.reduce((_target, _key) => {
			return add([_target, item[_key]], 2)
		}, 0)
		if (item.type === '+') {
			return add([target, sum], 2);
		} else {
			return subtract([target, sum], 2);
		}
	}, 0)
	info.value.amount = add([info.value.with_tax_amount, info.value.deduct_amount], 2)
}, { deep: true })
const toReturn = () => {
	const from = query.from;
	closeTab(from || '/settlement/apply')
}
const closeTab = inject("closeTab");
</script>
<style scoped lang="scss">
.settlement-manage-container {
  background: #fff;
  padding: 12px;
  :deep .ant-collapse-header{
    padding: 0 !important
  }
  :deep .ant-collapse-content-box{
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
}
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  .page {
    width: 600px;
    & .underline{
      border-bottom: 1px solid black;
    }
  }
}
</style>